#include"TcpServer.h"
#include<QString>
#include<QTcpServer>
#include<QTcpSocket>
#include<QWebSocket>
#include<QJsonDocument>
#include<QJsonObject>
#include<QJsonArray>
#include"mainwindow.h"
#include<QMap>
#include<QEventLoop>
#include<QThread>
#include<database.h>
#include<QtMath>
#include<QTimer>
#include<QTextEdit>

#define N 10;
QMap<QString,QString> m={{"name","base"},{"track_id","listennum"},{"agentId","agentinfo"}};
TcpServer::TcpServer(QString ip,int port):QThread(){//构造函数
    this->ip=QHostAddress(ip);
    this->port=port;
    localization = new TOALocalization(this);
    connect(this->localization,&TOALocalization::pointCalculated,this,[=](QString p,double x,double y){
        double x1=x/100;
        double y1=y/100;//单位转换
        QMap<QString,QString> map;
        map.insert("pos",QString("%1,0,%2").arg(x1).arg(y1));
        map.insert("agentId",p);
        DataBase::getInstance().handerData("agentinfo",map,"agentId");
    });
}

TcpServer::~TcpServer(){//析构函数
    delete this->mTcpServer;//删除指针指向的内存
}

void TcpServer::TcpServer::mStart(){
    this->mTcpServer=new QTcpServer();//将对象创建在子线程中
    qDebug()<<"开始监听TCP连接"<<this->ip<<"  "<<this->port;
    connect(this->mTcpServer, &QTcpServer::newConnection, this, &TcpServer::newClient);
    if(!this->mTcpServer->listen(this->ip,this->port))//监听指定IP和端口
    {
        perror("监听错误:");
    }
}

void TcpServer::newClient(){
    qDebug()<<"新的TCP连接";
    QTcpSocket* socket = this->mTcpServer->nextPendingConnection();//建立连接的套接字
    this->sockets[socket]=1;
    emit(this->sendC("客户端连接成功...",SendContent::CONNECT));//
    connect(socket, &QTcpSocket::readyRead, this,[=](){
        readEvent(socket);
    });//读事件
    connect(socket,&QTcpSocket::disconnected,this,[=](){
        disconnected(socket);
        qDebug()<<"断开连接";
    });//断开连接
}

void TcpServer::readEvent(QTcpSocket* socket){

    // uint8_t len;
    // socket->read((char*)&len,sizeof(uint8_t));
    // QString s;
    // socket->read((char*)&s,sizeof(len));
    // qDebug()<<len<<s;
    QByteArray bytearr=socket->readAll();
    QString s=QString::fromUtf8(bytearr);//将内容转化为字符
    emit(this->sendM(s));//将信号发送给主线程
    qDebug()<<"收到的信息："<<s;

    QMap<QString,QString> map;
    int begin=0;
    QString tab;
    qDebug()<<s;
    QString name1;
    while(begin<s.size()){
        int posb=s.indexOf(":",begin);
        int posEnd=s.indexOf("\r\n",begin);
        QString name;
        QString data;
        name=s.mid(begin,posb-begin);
        data=s.mid(posb+1,posEnd-posb-1);
        if(begin==0){
            tab=m.find(name).value();
            name1=name;
        }
        map[name]=data;
        begin=posEnd+2;
    }
    auto it=map.find("agentId");
    if(!it->isEmpty()&&s.size()<70){
        //基站定位
        dateProcess(map,it.value());
    }else{
        it=map.find("d1");
        if(!it->isEmpty()) map.erase(it);
        it=map.find("d2");
        if(!it->isEmpty()) map.erase(it);
        it=map.find("d3");
        if(!it->isEmpty()) map.erase(it);//需要结算的数据不写入数据库
         DataBase::getInstance().handerData(tab,map,name1);
    }
}

void TcpServer::dateProcess(QMap<QString,QString> m,QString id)
{
    // 严格的格式检查
    if(m.isEmpty()) {
        qDebug() << "收到空消息";
        return;
    }

    // 验证三个距离均已传到
    if(m.find("d1")->isEmpty()||m.find("d2")->isEmpty()||m.find("d3")->isEmpty()) {
        qDebug() << "消息格式错误，缺少必要分隔符";
        return;
    }

    try {
        // 基站1
        QString str3 = m.find("d1").value();
        // 基站2
        QString str4 = m.find("d2").value();
        // 基站3
        QString str5 = m.find("d3").value();
        qDebug()<<str3<<"  "<<str4<<"  "<<str5;
        // 转换数据
        bool  ok3, ok4, ok5;
        double an1_data = str3.toFloat(&ok3)*N;
        double an2_data = str4.toFloat(&ok4)*N;
        double an3_data = str5.toFloat(&ok5)*N;

        if( !ok3 || !ok4 || !ok5) {
            qDebug() << "数据转换失败";
            return;
        }
        // 更新定位数据
        qDebug()<<an1_data<<"  "<<an2_data<<"  "<<an3_data;
        QVector<double> distances = {an1_data, an2_data, an3_data};
        localization->updateMeasurements(distances);
        processData(id);
    } catch (...) {
        qDebug() << "处理数据时发生异常";
    }
    qDebug()<<"1";
}

void TcpServer::dateProcess(const QString &message)
{
    // 严格的格式检查
    if(message.isEmpty()) {
        qDebug() << "收到空消息";
        return;
    }

    // 检查所有必需的分隔符是否存在
    int d_pos = message.indexOf("d");
    int e_pos = message.indexOf("e");
    int g_pos = message.indexOf("g");
    int h_pos = message.indexOf("h");

    // 验证所有分隔符都存在且顺序正确
    if(d_pos == -1 || e_pos == -1 || g_pos == -1 || h_pos == -1) {
        qDebug() << "消息格式错误，缺少必要分隔符";
        return;
    }

    if(!(d_pos < e_pos && e_pos < g_pos && g_pos < h_pos)){
        qDebug() << "分隔符顺序不正确";
        return;
    }

    try {
        // 基站1(d-e)
        QString str3 = message.mid(d_pos+1, e_pos-d_pos-1);
        // 基站2(e-g)
        QString str4 = message.mid(e_pos+1, g_pos-e_pos-1);
        // 基站3(g-h)
        QString str5 = message.mid(g_pos+1, h_pos-g_pos-1);

        // 转换数据
        bool  ok3, ok4, ok5;
        double an1_data = str3.toFloat(&ok3)*N;
        double an2_data = str4.toFloat(&ok4)*N;
        double an3_data = str5.toFloat(&ok5)*N;
        if( !ok3 || !ok4 || !ok5) {
            qDebug() << "数据转换失败";
            return;
        }
        // 更新定位数据
        QVector<double> distances = {an1_data, an2_data, an3_data};
        localization->updateMeasurements(distances);
        //processData();
    } catch (...) {
        qDebug() << "处理数据时发生异常";
    }
}

void TcpServer::processData(QString id)
{
    if(localization->calculateNextPoint(id)) {//计算坐标成功
        // Data processed successfully
    } else {
        // All points processed, reset for new data
        localization->resetCalculation();
    }
    qDebug()<<"2";
}


void TcpServer::sendEvent(QByteArray jsonCont){
    m_mutex->lock();
    int n=0;
    for(auto it=webSocketM.begin();it!=webSocketM.end();it++){
        emit(this->sendWebSocket("山海鲸"+QString::number(n)+":"+QString::fromUtf8(jsonCont)));//将信号发送给主线程
        it.key()->sendTextMessage(jsonCont);
    }
    m_mutex->unlock();
}

void TcpServer::disconnected(QTcpSocket* socket){
    delete socket;//删除断开连接的套接字
    emit(this->sendC("TCP客户端断开连接...",SendContent::DEL));
}

void TcpServer::run(){
    this->mStart();
    exec();
}

void TcpServer::getKV(QString& s,int &begin,QString &key,QString &value){//获取键值对
    int posb=s.indexOf(":",begin);
    int posEnd=s.indexOf("\r\n",begin);
    key=s.mid(begin,posb-begin);
    value=s.mid(posb+1,posEnd-posb-1);
    begin=posEnd+2;
}
double TcpServer::getDistance(QVector<double>& v1,QVector<double>& v2){//计算两点之间的距离
    double ans=0;
    for(int i=0;i<3;i++){
        ans+=(v1[i]-v2[i])*(v1[i]-v2[i]);
    }
    ans=qSqrt(ans);
}


